<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品列表</title>
    <style>
        /**
         * 商品列表页面样式
         * 
         * 样式结构：
         * 1. 全局样式
         * 2. 导航栏样式
         * 3. 商品网格布局
         * 4. 商品卡片样式
         * 5. 搜索框样式
         * 6. 分页控件样式
         * 7. 加载状态样式
         */

        /* 全局样式重置 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        /* 导航栏样式 */
        h1 {
            width: 100%;
            height: 80px;
            background-color: skyblue;
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;
        }

        /* 返回首页链接样式 */
        .back-home {
            position: absolute;
            right: 50px;
            top: 50%;
            transform: translateY(-50%);
        }

        .back-home a {
            color: white;
            text-decoration: none;
        }

        /* 主容器样式 */
        .container {
            width: 1200px;
            margin: 20px auto;
            padding: 20px;
        }

        /* 商品网格布局 - 使用Grid实现响应式布局 */
        .products {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 20px;
        }

        /* 商品卡片样式 - 包含悬停效果 */
        .product-card {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            text-align: center;
            transition: transform 0.3s;
        }

        .product-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        /* 商品图片样式 - 统一尺寸和展示效果 */
        .product-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
            border-radius: 4px;
            margin-bottom: 10px;
        }

        /* 商品标题样式 */
        .product-title {
            font-size: 18px;
            margin-bottom: 10px;
            color: #333;
        }

        /* 价格信息样式 - 包含折扣显示 */
        .price-info {
            margin-bottom: 10px;
        }

        .product-price {
            color: #e4393c;
            font-size: 20px;
            font-weight: bold;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .original-price {
            color: #999;
            font-size: 14px;
            text-decoration: line-through;
            font-weight: normal;
        }

        .discount {
            background-color: #e4393c;
            color: white;
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 12px;
        }

        /* 商品操作按钮样式 */
        .product-buttons {
            display: flex;
            gap: 10px;
            justify-content: center;
        }

        .product-button {
            background-color: #e4393c;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .product-button:hover {
            background-color: #c81623;
        }

        .add-to-cart {
            background-color: #ff9900;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .add-to-cart:hover {
            background-color: #ff8800;
        }

        /* 搜索框样式 */
        .search-container {
            width: 1200px;
            margin: 20px auto;
            display: flex;
            gap: 10px;
        }

        .search-input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }

        .search-button {
            padding: 10px 20px;
            background: skyblue;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .search-button:hover {
            background: #5cacee;
        }

        /* 分页控件样式 */
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 20px;
            margin: 30px 0;
        }

        .page-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .page-input {
            width: 60px;
            height: 30px;
            text-align: center;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 0 5px;
        }

        /* 分页按钮样式 */
        .prev-page,
        .next-page,
        .go-to-page {
            padding: 8px 15px;
            border: 1px solid #ddd;
            background: white;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .prev-page:hover,
        .next-page:hover,
        .go-to-page:hover {
            background: #f5f5f5;
        }

        .prev-page:disabled,
        .next-page:disabled {
            background: #f5f5f5;
            cursor: not-allowed;
            opacity: 0.6;
        }

        .go-to-page {
            background: #ff9900;
            color: white;
            border: none;
        }

        .go-to-page:hover {
            background: #ff8800;
        }

        /* 加载状态样式 - 包含遮罩层和旋转动画 */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            visibility: hidden;
            opacity: 0;
            transition: all 0.3s;
        }

        .loading-overlay.active {
            visibility: visible;
            opacity: 1;
        }

        .loading-spinner {
            width: 50px;
            height: 50px;
            border: 5px solid #f3f3f3;
            border-top: 5px solid skyblue;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <!-- 主页面容器 - 默认隐藏，登录后显示 -->
    <div id="app" style="display: none">
        <!-- 导航栏 -->
        <h1>
            商品列表
            <div class="back-home">
                <a href="/pages/cart/index.html" style="color: white; text-decoration: none; margin-right: 20px;">购物车</a>
                <a href="/pages/index.html" style="color: white; text-decoration: none;">返回首页</a>
            </div>
        </h1>

        <!-- 搜索框 -->
        <div class="search-container">
            <input type="text" class="search-input" placeholder="搜索商品...">
            <button class="search-button">搜索</button>
        </div>

        <!-- 商品列表容器 -->
        <div class="container">
            <div class="products"></div>
        </div>

        <!-- 分页控件 -->
        <div class="pagination">
            <button class="prev-page">上一页</button>
            <div class="page-info">
                <span>第 <input type="number" class="page-input" min="1"> 页</span>
                <span>/ 共 <span class="total-pages">1</span> 页</span>
                <button class="go-to-page">跳转</button>
            </div>
            <button class="next-page">下一页</button>
        </div>

        <!-- 加载状态指示器 -->
        <div class="loading-overlay">
            <div class="loading-spinner"></div>
        </div>
    </div>

    <!-- 引入必要的JavaScript库和模块 -->
    <script src="/assets/libs/axios/axios.min.js"></script>
    <script src="/assets/js/http.js"></script>
    <script src="/assets/js/auth-check.js"></script>
    <script>
        /**
         * 商品列表页面的JavaScript逻辑
         * 
         * 依赖模块：
         * - axios: HTTP请求库
         * - http.js: 自定义HTTP请求和认证模块
         * - auth-check.js: 登录状态检查模块
         * 
         * 主要功能：
         * 1. 登录状态验证
         * 2. 商品列表加载和展示
         * 3. 搜索功能
         * 4. 分页控制
         * 5. 购物车操作
         */

        /**
         * 登录状态检查函数
         * 调用auth-check.js中的isLogin函数验证登录状态
         * 未登录时重定向到登录页面
         */
        async function checkAuth() {
            const loginStatus = await isLogin();
            if (loginStatus.status !== 1) {
                alert('请先登录后再访问商品列表！');
                window.location.href = '/pages/auth/login.html';
                return false;
            }
            document.getElementById('app').style.display = 'block';
            return true;
        }

        // 页面加载时检查登录状态并加载商品
        window.addEventListener('load', async () => {
            if (await checkAuth()) {
                loadProducts(1);
            }
        });

        // 获取DOM元素
        const productsContainer = document.querySelector('.products');

        // 加载状态控制对象
        const loading = {
            show() {
                document.querySelector('.loading-overlay').classList.add('active');
            },
            hide() {
                document.querySelector('.loading-overlay').classList.remove('active');
            }
        };

        // 分页相关变量
        let currentPage = 1;
        const pageSize = 12;  // 每页显示12个商品
        let totalPages = 1;

        // 搜索功能相关元素
        const searchInput = document.querySelector('.search-input');
        const searchButton = document.querySelector('.search-button');

        // 添加搜索事件监听
        searchButton.addEventListener('click', () => {
            const keyword = searchInput.value.trim();
            loadProducts(1, keyword);  // 搜索时重置到第一页
        });

        // 添加搜索框回车事件
        searchInput.addEventListener('keyup', (e) => {
            if (e.key === 'Enter') {
                const keyword = searchInput.value.trim();
                loadProducts(1, keyword);
            }
        });

        // 分页相关元素
        const pageInput = document.querySelector('.page-input');
        const goToPageBtn = document.querySelector('.go-to-page');

        /**
         * 更新页码输入框显示
         * @param {number} page - 当前页码
         */
        function updatePageInput(page) {
            pageInput.value = page;
        }

        // 初始化页码输入框
        updatePageInput(currentPage);

        // 添加页码跳转事件
        goToPageBtn.addEventListener('click', () => {
            const targetPage = parseInt(pageInput.value);
            if (targetPage && targetPage >= 1 && targetPage <= totalPages) {
                currentPage = targetPage;
                loadProducts(currentPage);
                window.scrollTo({ top: 0, behavior: 'smooth' });
            } else {
                alert('请输入有效的页码！');
                updatePageInput(currentPage);
            }
        });

        // 添加页码输入框回车事件
        pageInput.addEventListener('keyup', (e) => {
            if (e.key === 'Enter') {
                goToPageBtn.click();
            }
        });

        /**
         * 加载商品列表
         * 使用http.js中的get方法请求商品数据
         * 
         * @param {number} page - 页码
         * @param {string} keyword - 搜索关键词
         */
        async function loadProducts(page = 1, keyword = '') {
            try {
                loading.show();
                // 构建请求参数
                const params = {
                    current: page,
                    pagesize: pageSize
                };
                if (keyword) {
                    params.keyword = keyword;
                }

                // 发送请求获取商品列表
                const response = await http.get('/goods/list', { params });
                
                // 处理响应数据
                if (response.data.code === 1) {
                    productsContainer.innerHTML = '';
                    
                    const products = response.data.list;
                    if (products && products.length > 0) {
                        // 渲染商品列表
                        products.forEach(product => {
                            const productCard = `
                                <div class="product-card">
                                    <img src="${product.img_big_logo}" alt="${product.title}" class="product-image">
                                    <h3 class="product-title">${product.title}</h3>
                                    <div class="price-info">
                                        <p class="product-price">
                                            ￥${product.current_price}
                                            ${product.is_sale ? `<span class="original-price">￥${product.price}</span>` : ''}
                                            ${product.is_sale ? `<span class="discount">${product.sale_type}</span>` : ''}
                                        </p>
                                    </div>
                                    <div class="product-buttons">
                                        <button class="product-button" onclick="location.href='/pages/products/detail.html?id=${product.goods_id}'">
                                            查看详情
                                        </button>
                                        <button class="add-to-cart" onclick="addToCart({
                                            goods_id: ${product.goods_id},
                                            title: '${product.title.replace(/'/g, "\\'")}',
                                            img_big_logo: '${product.img_big_logo}',
                                            current_price: ${product.current_price}
                                        })">
                                            加入购物车
                                        </button>
                                    </div>
                                </div>
                            `;
                            productsContainer.insertAdjacentHTML('beforeend', productCard);
                        });

                        // 更新分页信息
                        totalPages = Math.ceil(response.data.total / pageSize);
                        document.querySelector('.total-pages').textContent = totalPages;
                        updatePageInput(page);
                        
                        // 更新分页按钮状态
                        document.querySelector('.prev-page').disabled = page === 1;
                        document.querySelector('.next-page').disabled = page === totalPages;
                    } else {
                        productsContainer.innerHTML = '<p style="text-align: center; grid-column: 1/-1;">暂无商品数据</p>';
                    }
                } else {
                    throw new Error(response.data.message || '加载商品列表失败');
                }
            } catch (error) {
                console.error('获取商品列表失败:', error);
                productsContainer.innerHTML = '<p style="text-align: center; grid-column: 1/-1;">加载商品列表失败</p>';
            } finally {
                loading.hide();
            }
        }

        // 添加分页按钮事件监听
        document.querySelector('.prev-page').addEventListener('click', () => {
            if (currentPage > 1) {
                currentPage--;
                loadProducts(currentPage);
                window.scrollTo({ top: 0, behavior: 'smooth' });
            }
        });

        document.querySelector('.next-page').addEventListener('click', () => {
            if (currentPage < totalPages) {
                currentPage++;
                loadProducts(currentPage);
                window.scrollTo({ top: 0, behavior: 'smooth' });
            }
        });

        /**
         * 添加商品到购物车
         * 使用localStorage存储购物车数据
         * 
         * @param {Object} product - 商品信息对象
         * - goods_id: 商品ID
         * - title: 商品标题
         * - img_big_logo: 商品图片
         * - current_price: 当前价格
         */
        async function addToCart(product) {
            // 调用auth-check.js中的isLogin函数检查登录状态
            const loginStatus = await isLogin();
            if (loginStatus.status !== 1) {
                alert('请先登录后再添加商品到购物车！');
                window.location.href = '/pages/auth/login.html';
                return;
            }

            // 从 localStorage 获取购物车数据
            let cart = JSON.parse(localStorage.getItem('cart') || '[]');
            
            // 检查商品是否已在购物车中
            const existingItem = cart.find(item => item.goods_id === product.goods_id);
            
            if (existingItem) {
                // 如果商品已存在，增加数量
                existingItem.quantity += 1;
            } else {
                // 如果商品不存在，添加到购物车
                cart.push({
                    ...product,
                    quantity: 1
                });
            }
            
            // 保存到 localStorage
            localStorage.setItem('cart', JSON.stringify(cart));
            
            // 显示提示
            alert('已添加到购物车！');
        }

        // 更新分页按钮状态
function updatePagination(response) {
    totalPages = response.data.totalPages;
    document.querySelector('.total-pages').textContent = totalPages;

    // 更新按钮状态
    document.querySelector('.prev-page').disabled = currentPage <= 1;
    document.querySelector('.next-page').disabled = currentPage >= totalPages;
}

// 分页按钮事件
document.querySelector('.prev-page').addEventListener('click', () => {
    if (currentPage > 1) {
        currentPage--;
        loadProducts(currentPage);
    }
});

document.querySelector('.next-page').addEventListener('click', () => {
    if (currentPage < totalPages) {
        currentPage++;
        loadProducts(currentPage);
    }
});

// 搜索功能
searchButton.addEventListener('click', () => {
    const keyword = searchInput.value.trim();
    loadProducts(1, keyword);  // 重置到第一页并搜索
});

// 加载商品列表并更新分页
async function loadProducts(page = 1, keyword = '') {
    try {
        loading.show();
        const params = {
            current: page,
            pagesize: pageSize,
            keyword: keyword
        };

        const response = await http.get('/goods/list', { params });

        // 更新商品列表
        if (response.data.code === 1) {
            productsContainer.innerHTML = '';
            const products = response.data.list;
            products.forEach(product => {
                const productCard = `
                    <div class="product-card">
                        <img src="${product.img_big_logo}" alt="${product.title}" class="product-image">
                        <div class="product-title">${product.title}</div>
                        <div class="price-info">
                            <span class="product-price">${product.price}</span>
                            ${product.discount ? `<span class="discount">${product.discount}</span>` : ''}
                        </div>
                        <div class="product-buttons">
                            <button class="product-button">查看</button>
                            <button class="add-to-cart">加入购物车</button>
                        </div>
                    </div>
                `;
                productsContainer.innerHTML += productCard;
            });
            
            // 更新分页控件状态
            updatePagination(response);
        } else {
            alert('商品加载失败');
        }
    } catch (error) {
        console.error('加载商品列表失败:', error);
    } finally {
        loading.hide();
    }
}
    </script>
</body>
</html> 